package com.sptpc.stu.controller;

import cn.hutool.core.bean.BeanUtil;
import com.sptpc.stu.common.controller.BaseController;
import com.sptpc.stu.common.response.JSONResponse;
import com.sptpc.stu.common.utils.QueryPage;
import com.sptpc.stu.controller.request.EditCourseRequest;
import com.sptpc.stu.controller.request.EditStudentRequest;
import com.sptpc.stu.controller.request.NewCourseRequest;
import com.sptpc.stu.controller.request.NewStudentRequest;
import com.sptpc.stu.model.Course;
import com.sptpc.stu.model.Major;
import com.sptpc.stu.model.Student;
import com.sptpc.stu.repository.CourseRepository;
import com.sptpc.stu.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/cur")
public class CourseController  extends BaseController  {
    @Autowired
    private CourseRepository courseRepository;


    // 新建课程，json格式传数据
//    @PostMapping(value = "/add", consumes = MediaType.APPLICATION_JSON_VALUE)
//    public Course addNewCourse(@RequestBody Course course) {
//        // 课程信息写入数据库
//        courseRepository.save(course);
//        return course;
//    }


    @PostMapping(value = "/add",
            consumes = MediaType.APPLICATION_JSON_VALUE)
    public JSONResponse addNewCourse(@RequestBody NewCourseRequest courseRequest) {

        Course saveCourse = new Course();
        BeanUtil.copyProperties(courseRequest, saveCourse);


        courseRepository.save(saveCourse);

        return JSONResponse.ofSuccess();
    }


    // 得到所有的课程
    @GetMapping(value = "/list")
    public JSONResponse getAllCourse(QueryPage queryPage) {


        Page<Course> page = courseRepository.findAll(PageRequest.of(queryPage.getPage() - 1,queryPage.getLimit()));


        return JSONResponse.ofSuccess(getData(page));

    }



    @PutMapping(value = "/update", consumes = MediaType.APPLICATION_JSON_VALUE)
    public JSONResponse updateCourse(@RequestBody EditCourseRequest cor) {

        Optional<Course> optional =
                courseRepository.findById(cor.getId());

        if (optional.isPresent()) {
            Course course = optional.get();
            BeanUtil.copyProperties(cor, course);
            System.out.println(cor.getCid() + cor.getCoursePoints() + cor.getCourseTime() + cor.getName());
            courseRepository.saveAndFlush(course);
            return JSONResponse.ofSuccess();
        }

        return JSONResponse.ofFail("课程id不存在");
    }


}
